package cn.wgx.commons.util;

import cn.wgx.commons.config.Global;
import com.alibaba.fastjson.JSONObject;
import com.drew.imaging.FileType;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.image.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 图片处理工具类：<br>
 * 功能：缩放图像、切割图像、图像类型转换、彩色转黑白、文字水印、图片水印等
 *
  @author wgx
 */
public class ImageUtils {
    protected static Logger logger = LoggerFactory.getLogger(ImageUtils.class);
    /**
     * 根据Exif2.1标准，元数据信息包含：
     * Image Description 图像描述、来源. 指生成图像的工具
     * Artist 作者 有些相机可以输入使用者的名字
     * Make 生产者 指产品生产厂家
     * Model 型号 指设备型号
     * Orientation方向 有的相机支持，有的不支持
     * XResolution/YResolution X/Y方向分辨率 本栏目已有专门条目解释此问题。
     * ResolutionUnit分辨率单位 一般为PPI
     * Software软件 显示固件Firmware版本
     * DateTime日期和时间
     * YCbCrPositioning 色相定位
     * ExifOffsetExif信息位置，定义Exif在信息在文件中的写入，有些软件不显示。
     * ExposureTime 曝光时间 即快门速度
     * FNumber光圈系数
     * ExposureProgram曝光程序 指程序式自动曝光的设置，各相机不同,可能是Sutter Priority（快门优先）、Aperture Priority（快门优先）等等。
     * ISO speed ratings感光度
     * ExifVersionExif版本
     * DateTimeOriginal创建时间
     * DateTimeDigitized数字化时间
     * ComponentsConfiguration图像构造（多指色彩组合方案）
     * CompressedBitsPerPixel(BPP)压缩时每像素色彩位 指压缩程度
     * ExposureBiasValue曝光补偿。
     * MaxApertureValue最大光圈
     * MeteringMode测光方式， 平均式测光、中央重点测光、点测光等。
     * Lightsource光源 指白平衡设置
     * Flash是否使用闪光灯。
     * FocalLength焦距，一般显示镜头物理焦距，有些软件可以定义一个系数，从而显示相当于35mm相机的焦距 MakerNote(User Comment)作者标记、说明、记录
     * FlashPixVersionFlashPix版本 （个别机型支持）
     * ColorSpace色域、色彩空间
     * ExifImageWidth(Pixel X Dimension)图像宽度 指横向像素数
     * ExifImageLength(Pixel Y Dimension)图像高度 指纵向像素数
     * Interoperability IFD通用性扩展项定义指针 和TIFF文件相关，具体含义不详
     * FileSource源文件 Compression压缩比。
     *  */

    public static Integer ZOO_MIN_WIDTH = 1000;

    public static String DEFAULT_WATERMARK = "中科北影";

    public static Font DEFAULT_FONT = new Font("宋体",Font.BOLD + Font.ITALIC,50);

    public static Color DEFAULT_COLOR = new Color(247,221,110);

    static {
        String pro_width = Global.getConfig("ZOO_MIN_WIDTH");
        if (pro_width != null) {
            try {
                ZOO_MIN_WIDTH = Integer.parseInt(pro_width);
            } catch (NumberFormatException e) {
                logger.info("配置文件缩略图最小宽度: ZOO_MIN_WIDTH 错误 : " + pro_width + ", 使用默认宽度: " + ZOO_MIN_WIDTH);
            }
        }
    }
    /**
     * 几种常见的图片格式
     */
    public static final String IMAGE_TYPE_GIF = "gif";// 图形交换格式
    public static final String IMAGE_TYPE_JPG = "jpg";// 联合照片专家组
    public static final String IMAGE_TYPE_JPEG = "jpeg";// 联合照片专家组
    public static final String IMAGE_TYPE_BMP = "bmp";// 英文Bitmap（位图）的简写，它是Windows操作系统中的标准图像文件格式
    public static final String IMAGE_TYPE_PNG = "png";// 可移植网络图形
    public static final String IMAGE_TYPE_PSD = "psd";// Photoshop的专用格式Photoshop


    /**
     * 获取图像MetaData
     *
     * @param jpegFile
     * @return
     * @throws ImageProcessingException
     * @throws IOException
     */
    public static JSONObject getMetaData(File jpegFile) throws ImageProcessingException, IOException {
        Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
        JSONObject map = new JSONObject();
        for (Directory directory : metadata.getDirectories()) {
            JSONObject o = new JSONObject();
            for (Tag tag : directory.getTags()) {
                o.put(tag.getTagName(), tag.getDescription());
            }
            map.put(directory.getName(), o);
        }
        return map;
    }

    /**
     * 获取图像MetaData
     *
     * @param jpegFile
     * @param ext
     * @return
     * @throws ImageProcessingException
     * @throws IOException
     */
    public static JSONObject getMetaData(byte[] jpegFile, String ext) throws ImageProcessingException, IOException {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(jpegFile);
        Metadata metadata = ImageMetadataReader.readMetadata(byteArrayInputStream, new Long(jpegFile.length), getFileTypeByExt(ext));
        JSONObject map = new JSONObject();
        for (Directory directory : metadata.getDirectories()) {
            JSONObject o = new JSONObject();
            for (Tag tag : directory.getTags()) {
                o.put(tag.getTagName(), tag.getDescription());
            }
            map.put(directory.getName(), o);
        }
        return map;
    }

    public static BufferedImage zoomImageScale(File file) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(file);
        String ext = StringUtils.getFileExt(file.getName());
        return zoomImageScale(bufferedImage, ext);
    }

    public static BufferedImage zoomImageScale(byte[] file, String ext) throws IOException {
        BufferedImage bufferedImage = ImageUtils.getBufferedImageByFile(file);
        return zoomImageScale(bufferedImage, ext);
    }

    public static BufferedImage zoomImageScale(BufferedImage bufferedImage, String ext) {
        if (null == bufferedImage)
            return null;
        int originalWidth = bufferedImage.getWidth();
        int originalHeight = bufferedImage.getHeight();
        double scale = (double) originalWidth / (double) ZOO_MIN_WIDTH;    // 缩放的比例
        int newHeight;
        if (scale <= 1) {
          newHeight = originalHeight;
            ZOO_MIN_WIDTH = originalWidth;
        } else {
            newHeight = (int) (originalHeight / scale);
        }
        return zoomImageUtils(bufferedImage, ZOO_MIN_WIDTH, newHeight, ext);
    }

    private static BufferedImage zoomImageUtils(BufferedImage bufferedImage, int width, int height, String ext) {

        BufferedImage newImage = null;
        // 处理 png 背景变黑的问题
        if (ext != null && (ext.trim().toLowerCase().endsWith("png") || ext.trim().toLowerCase().endsWith("gif"))) {
            newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = newImage.createGraphics();
            newImage = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
            g2d.dispose();
            g2d = newImage.createGraphics();
            Image from = bufferedImage.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
            g2d.drawImage(from, 0, 0, null);
            g2d.dispose();
        } else {
            newImage = new BufferedImage(width, height, bufferedImage.getType());
            Graphics g = newImage.getGraphics();
            g.drawImage(bufferedImage, 0, 0, width, height, null);
            g.dispose();
        }
        return newImage;
    }


    /**
     * 缩放图像（按比例缩放）
     *
     * @param src   源图像文件地址
     * @param scale 缩放比例
     * @param flag  缩放选择:true 放大; false 缩小;
     */
    public final static BufferedImage scale(BufferedImage src,
                                            int scale, boolean flag) {
        int width = src.getWidth(); // 得到源图宽

        int height = src.getHeight(); // 得到源图长

        int newWidth = 0;
        if (flag) {// 放大
            width = width * scale;
            height = height * scale;
        } else {// 缩小
            width = width / scale;
            height = height / scale;
        }
        Image image = src.getScaledInstance(width, height,
                Image.SCALE_DEFAULT);
        BufferedImage tag = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.drawImage(image, 0, 0, null); // 绘制缩放后的图

        g.dispose();
        return tag;
    }

    /**
     * 缩放图像（按高度和宽度缩放）
     *
     * @param height 缩放后的高度
     * @param width  缩放后的宽度
     * @param bb     比例不对时是否需要补白：true为补白; false为不补白;
     */
    public final static BufferedImage scaleByWH(BufferedImage bufferedImage, int width, int height, boolean bb) {
        double ratio = 0.0; // 缩放比例
        Image itemp = bufferedImage.getScaledInstance(width, height, bufferedImage.SCALE_SMOOTH);
        // 计算比例
        if ((bufferedImage.getHeight() > height) || (bufferedImage.getWidth() > width)) {
            if (bufferedImage.getHeight() > bufferedImage.getWidth()) {
                ratio = (new Integer(height)).doubleValue()
                        / bufferedImage.getHeight();
            } else {
                ratio = (new Integer(width)).doubleValue() / bufferedImage.getWidth();
            }
            AffineTransformOp op = new AffineTransformOp(AffineTransform
                    .getScaleInstance(ratio, ratio), null);
            itemp = op.filter(bufferedImage, null);
        }
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        if (bb) {//补白
            Graphics2D g = image.createGraphics();
            g.setColor(Color.white);
            g.fillRect(0, 0, width, height);
            if (width == itemp.getWidth(null))
                g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,
                        itemp.getWidth(null), itemp.getHeight(null),
                        Color.white, null);
            else
                g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,
                        itemp.getWidth(null), itemp.getHeight(null),
                        Color.white, null);
            g.dispose();
            itemp = image;
        }
        return image;
    }

    /**
     * 缩放图像（按高度和宽度缩放）
     *
     * @param height 缩放后的高度
     * @param width  缩放后的宽度
     * @param bb     比例不对时是否需要补白：true为补白; false为不补白;
     */
    public final static BufferedImage scale3(BufferedImage src, int width, int height, boolean bb) {
        //int _width = src.getWidth(); // 得到源图宽
        //int _height = src.getHeight(); // 得到源图长
        Image image = src.getScaledInstance(width, height,
                Image.SCALE_DEFAULT);
        BufferedImage tag = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.drawImage(image, 0, 0, null); // 绘制缩小后的图
        return tag;
    }

    /**
     * 图像切割(按指定起点坐标和宽高切割)
     *
     * @param x      目标切片起点坐标X
     * @param y      目标切片起点坐标Y
     * @param width  目标切片宽度
     * @param height 目标切片高度
     */
    public final static BufferedImage cut(BufferedImage bi,
                                          int x, int y, int width, int height) {
        // 读取源图像
        int srcWidth = bi.getHeight(); // 源图宽度
        int srcHeight = bi.getWidth(); // 源图高度
        if (srcWidth > 0 && srcHeight > 0) {
            Image image = bi.getScaledInstance(srcWidth, srcHeight,
                    Image.SCALE_DEFAULT);
            // 四个参数分别为图像起点坐标和宽高
            // 即: CropImageFilter(int x,int y,int width,int height)
            ImageFilter cropFilter = new CropImageFilter(x, y, width, height);
            Image img = Toolkit.getDefaultToolkit().createImage(
                    new FilteredImageSource(image.getSource(),
                            cropFilter));
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(img, 0, 0, width, height, null); // 绘制切割后的图

            g.dispose();
            // 输出为文件

            return tag;
        } else {
            return bi;
        }
    }

    /**
     * 图像切割（指定切片的行数和列数）
     *
     * @param rows 目标切片行数。默认2，必须是范围 [1, 20] 之内
     * @param cols 目标切片列数。默认2，必须是范围 [1, 20] 之内
     */
    public final static List<BufferedImage> cut2(BufferedImage bi,
                                                 int rows, int cols) {
        if (rows <= 0 || rows > 20) rows = 2; // 切片行数
        if (cols <= 0 || cols > 20) cols = 2; // 切片列数
        // 读取源图像
        List<BufferedImage> list = new ArrayList<BufferedImage>();
        int srcWidth = bi.getHeight(); // 源图宽度
        int srcHeight = bi.getWidth(); // 源图高度
        if (srcWidth > 0 && srcHeight > 0) {
            Image img;
            ImageFilter cropFilter;
            Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
            int destWidth = srcWidth; // 每张切片的宽度

            int destHeight = srcHeight; // 每张切片的高度

            // 计算切片的宽度和高度
            if (srcWidth % cols == 0) {
                destWidth = srcWidth / cols;
            } else {
                destWidth = (int) Math.floor(srcWidth / cols) + 1;
            }
            if (srcHeight % rows == 0) {
                destHeight = srcHeight / rows;
            } else {
                destHeight = (int) Math.floor(srcWidth / rows) + 1;
            }
            // 循环建立切片
            // 改进的想法:是否可用多线程加快切割速度
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    // 四个参数分别为图像起点坐标和宽高
                    // 即: CropImageFilter(int x,int y,int width,int height)
                    cropFilter = new CropImageFilter(j * destWidth, i * destHeight,
                            destWidth, destHeight);
                    img = Toolkit.getDefaultToolkit().createImage(
                            new FilteredImageSource(image.getSource(),
                                    cropFilter));
                    BufferedImage tag = new BufferedImage(destWidth,
                            destHeight, BufferedImage.TYPE_INT_RGB);
                    Graphics g = tag.getGraphics();
                    g.drawImage(img, 0, 0, null); // 绘制缩小后的图

                    g.dispose();
                    list.add(tag);
                }
            }
        }
        return list;
    }

    /**
     * 图像切割（指定切片的宽度和高度）
     *
     * @param destWidth  目标切片宽度。默认200
     * @param destHeight 目标切片高度。默认150
     */
    public final static List<BufferedImage> cut3(BufferedImage bi,
                                                 int destWidth, int destHeight) {
        if (destWidth <= 0) destWidth = 200; // 切片宽度
        if (destHeight <= 0) destHeight = 150; // 切片高度
        List<BufferedImage> list = new ArrayList<BufferedImage>();
        int srcWidth = bi.getHeight(); // 源图宽度
        int srcHeight = bi.getWidth(); // 源图高度
        if (srcWidth > destWidth && srcHeight > destHeight) {
            Image img;
            ImageFilter cropFilter;
            Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
            int cols = 0; // 切片横向数量
            int rows = 0; // 切片纵向数量
            // 计算切片的横向和纵向数量
            if (srcWidth % destWidth == 0) {
                cols = srcWidth / destWidth;
            } else {
                cols = (int) Math.floor(srcWidth / destWidth) + 1;
            }
            if (srcHeight % destHeight == 0) {
                rows = srcHeight / destHeight;
            } else {
                rows = (int) Math.floor(srcHeight / destHeight) + 1;
            }
            // 循环建立切片
            // 改进的想法:是否可用多线程加快切割速度
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    // 四个参数分别为图像起点坐标和宽高
                    // 即: CropImageFilter(int x,int y,int width,int height)
                    cropFilter = new CropImageFilter(j * destWidth, i * destHeight,
                            destWidth, destHeight);
                    img = Toolkit.getDefaultToolkit().createImage(
                            new FilteredImageSource(image.getSource(),
                                    cropFilter));
                    BufferedImage tag = new BufferedImage(destWidth,
                            destHeight, BufferedImage.TYPE_INT_RGB);
                    Graphics g = tag.getGraphics();
                    g.drawImage(img, 0, 0, null); // 绘制缩小后的图

                    g.dispose();
                    list.add(tag);
                }
            }
        }
        return list;
    }

    /**
     * 图像类型转换：GIF->JPG、GIF->PNG、PNG->JPG、PNG->GIF(X)、BMP->PNG
     *
     * @param srcImageFile  源图像地址
     * @param formatName    包含格式非正式名称的 String：如JPG、JPEG、GIF等
     * @param destImageFile 目标图像地址
     */
    public final static void convert(String srcImageFile, String formatName, String destImageFile) {
        try {
            File f = new File(srcImageFile);
            f.canRead();
            f.canWrite();
            BufferedImage src = ImageIO.read(f);
            ImageIO.write(src, formatName, new File(destImageFile));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 彩色转为黑白
     */
    public final static BufferedImage gray(BufferedImage src) {
        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
        ColorConvertOp op = new ColorConvertOp(cs, null);
        src = op.filter(src, null);
        return src;
    }

    public final static BufferedImage pressDefaultText(BufferedImage src){

        return pressText(src, DEFAULT_WATERMARK, DEFAULT_FONT, DEFAULT_COLOR, 15, 15 ,0.5f);
    }

    /**
     * 给图片添加文字水印
     *
     * @param src       原始图片
     * @param pressText 水印文字
     * @param font      水印字体
     * @param color     水印的字体颜色
     * @param x         以图片中心位置 - 修正值
     * @param y         以图片中心位置 - 修正值
     * @param alpha     透明度：alpha 必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
     */
    public final static BufferedImage pressText(BufferedImage src,
                                                String pressText,
                                                Font font,
                                                Color color,
                                                int x, int y,
                                                float alpha) {
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        g.drawImage(src, 0, 0, width, height, null);
        g.setColor(color);
        g.setFont(font);
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                alpha));
        g.drawString(pressText,
                (width - (getLength(pressText) * font.getSize()))/ 2 + x,
                (height - font.getSize()) / 2 + y);
        g.dispose();
        return image;
    }

    public static BufferedImage getWaterMark(String pressText,
                                             Font font,
                                             Color color,
                                             int width, int height){
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        image = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g.dispose();
        g = image.createGraphics();
        g.setColor(color);
        g.setFont(font);
        g.drawString(pressText,0,font.getSize());
        g.dispose();
        return image;
    }

    /**
     * 给图片添加图片水印
     *
     * @param x             修正值。 默认在中间
     * @param y             修正值。 默认在中间
     * @param alpha         透明度：alpha 必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
     */
    public final static BufferedImage pressImage(BufferedImage src, BufferedImage src_biao,
                                        int x, int y, float alpha) {
            int wideth = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(wideth, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, wideth, height, null);

            int wideth_biao = src_biao.getWidth(null);
            int height_biao = src_biao.getHeight(null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    alpha));
            g.drawImage(src_biao, (wideth - wideth_biao) / 2,
                    (height - height_biao) / 2, wideth_biao, height_biao, null);
            // 水印文件结束
            g.dispose();
       return image;
    }

    /**
     * 创建图片缩略图(等比缩放 无失真缩放)
     *
     * @param width  缩放的宽度
     * @param height 缩放的高度
     * @param flag   true 按照实际长宽输出  如果 false 按照比例进行无失真压缩
     */
    public static BufferedImage createThumbnail(BufferedImage image, float width, float height, boolean flag) throws IOException {
        boolean flag1 = false;

        // 获得缩放的比例

        double ratio = 1.0;
        // 判断如果高、宽都不大于设定值，则不处理
        int height1 = image.getHeight();
        int width1 = image.getWidth();
        if (height1 > height || width1 > width) {
            if (height1 > width1) {
                ratio = height / height1;
            } else {
                ratio = width / width1;
            }
        }
        int newWidth = flag ? (int) width : (int) (width1 * ratio);
        int newHeight = flag ? (int) height : (int) (height1 * ratio);
        BufferedImage bfImage = new BufferedImage(newWidth, newHeight,
                BufferedImage.TYPE_INT_RGB);
        flag1 = bfImage.getGraphics().drawImage(
                image.getScaledInstance(newWidth, newHeight,
                        Image.SCALE_SMOOTH), 0, 0, null);

        return bfImage;
    }


    /**
     * 计算text的长度（一个中文算两个字符）
     *
     * @param text
     * @return
     */
    public final static int getLength(String text) {
        int length = 0;
        for (int i = 0; i < text.length(); i++) {
            if (new String(text.charAt(i) + "").getBytes().length > 1) {
                length += 2;
            } else {
                length += 1;
            }
        }
        return length / 2;
    }

    /**
     * 根据缓存对象存入File
     *
     * @param bfImage
     * @param dist
     * @throws IOException
     */
    public static void outputImage(BufferedImage bfImage, String dist) throws IOException {
//        FileOutputStream out = new FileOutputStream(dstName);
//        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//        encoder.encode(dstImage);
        String formatName = dist.substring(dist.lastIndexOf(".") + 1);
        ImageIO.write(bfImage, /*"GIF"*/ formatName /* format desired */ , new File(dist) /* target */ );
//        FileOutputStream os = new FileOutputStream(dist);
//        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
//        JPEGEncodeParam jParam = encoder.getDefaultJPEGEncodeParam(bfImage);
//        jParam.setQuality(1f, false);
//        encoder.encode(bfImage);
//        os.close();
    }

    /**
     * 根据图片缓存获取byte[]
     *
     * @param bufferedImage
     * @param ext
     * @return
     * @throws IOException
     */
    public static byte[] getBytesByImageBuffer(BufferedImage bufferedImage, String ext) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, ext, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }

    /**
     * 根据文件获取图片缓存对象
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static BufferedImage getBufferedImageByFile(File file) throws IOException {
        return ImageIO.read(file);
    }

    /**
     * 根据byte[]获取BufferedImage
     * @param file
     * @return
     * @throws IOException
     */
    public static BufferedImage getBufferedImageByFile(byte[] file) throws IOException {
        return ImageIO.read(new ByteArrayInputStream(file));
    }

    public static String getImageSize(BufferedImage bufferedImage){
        return bufferedImage.getWidth() +  " x " + bufferedImage.getHeight();
    }

    public static FileType getFileTypeByExt(String ext) {
        switch (ext) {
            case IMAGE_TYPE_JPG:
                return FileType.Jpeg;
            case IMAGE_TYPE_JPEG:
                return FileType.Jpeg;
            case IMAGE_TYPE_GIF:
                return FileType.Gif;
            case IMAGE_TYPE_BMP:
                return FileType.Bmp;
            case IMAGE_TYPE_PNG:
                return FileType.Png;
            case IMAGE_TYPE_PSD:
                return FileType.Psd;
            default:
                return FileType.Jpeg;
        }
    }
}